package com.my.demo.exception;

import com.my.demo.pojo.ErrorLog;
import com.my.demo.pojo.Result;
import com.my.demo.service.ErrorLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
//顶端的错误处理的Excetion
public class TopException {
  private Logger logger = LoggerFactory.getLogger(this.getClass());

  @Autowired
  ErrorLogService errorLogService;

  @ExceptionHandler(value = Exception.class)
  @ResponseBody
  public Result handle(Exception e) {
    Result result = new Result();
    result.setSuccess(false);
    result.setMsg("业务烦忙");
    result.setDetail(e);
    logger.error(e.getMessage());

    //写入错误日志
    ErrorLog errorLog = new ErrorLog(null, e.getMessage(), null);
    errorLogService.save(errorLog);

    return result;
  }
}

